/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ace.system;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 *
 * @author TimotiusNC
 */
public abstract class Model {
	public Model(){
	}

	public abstract void fromByteArray(byte[] data);
    public abstract byte[] toByteArray();

	/**
	 * Write model object into an RMS at index recordID
	 * RMS index is 1-based !!
	 * @param recordID
	 * @param model
	 * @return the actual index of the record inserted
	 */
	public static int writeModel(int recordID, Model model){
		RecordStore rs	= null;
		byte[] data		= null;
		int retval		= -1;

		try {
			rs = RecordStore.openRecordStore(Utilities.RMS_NAME, true);

			data = model.toByteArray();
			if(rs.getNextRecordID() > recordID+2) //overwrite, recordID+2 coz RMS is 1-based first record ID is reserved for ProfileCount
				rs.setRecord(recordID+2, data, 0, data.length);
			else									//create new
				retval = rs.addRecord(data, 0, data.length);
		} catch (RecordStoreFullException e) {
		} catch (RecordStoreNotFoundException e) {
		} catch (RecordStoreException e) {}
		finally {
			try {
				rs.closeRecordStore();
			} catch (RecordStoreNotOpenException e) {
			} catch (RecordStoreException e) {}
		}

		return retval;
	}

	/**
	 * Get array of bytes from RMS with index recordID
	 * RMS index is 1-based !!
	 * @param recordID
	 * @return array of bytes of record with index recordID
	 */
	public static byte[] getModelByteData(int recordID){
		RecordStore rs = null;
		byte[] retval = null;

		try {
			rs = RecordStore.openRecordStore(Utilities.RMS_NAME, true);

			if(rs.getNextRecordID() > recordID+2){ //recordID+2 coz RMS is 1-based first record ID is reserved for ProfileCount
				int size	= rs.getRecordSize(recordID+2);
				retval		= new byte[size];
				retval		= rs.getRecord(recordID+2);
			}
		} catch (RecordStoreFullException e) {
		} catch (RecordStoreNotFoundException e) {
		} catch (RecordStoreException e) {
		} finally {
			try {
				rs.closeRecordStore();
			} catch (RecordStoreNotOpenException e) {
			} catch (RecordStoreException e) {}
		}

		return retval;
	}
}
